<script>
	import {
		getOpenid
	} from '@/api/index.js'
	export default {
		onLaunch: function() {
			console.log('App Launch')
			console.log(window.location.href)
			let that = this
			uni.getStorage({
				key:'openid',
				success(res) {
					console.log('openidres',res)
				},
				fail(err) {
					console.log('openiderr',err)
					// that.getCode()
				}
			})
		},
		onShow: function() {
			console.log('App Show')
			// this.getOpenId()
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 获取code
			getCode() {
				// console.log('我进来了')
				let appid = "wx873a10f022021245"; //appid
				let local = encodeURIComponent('https://zhnc.pcippc.com/') //重定向回来的地址
				// console.log('local',local)
				let wx_code = this.getUrlParam("code")
				// 判断是否有Code
				if (!wx_code) {
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_base&state=1#wechat_redirect;`
				} else {
					// 接口传递code,获取openid
					this.getOpenId(wx_code)
				}
			},
			// 使用正则截取地址里的code
			getUrlParam(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
						location.href) || [, ''])[1]
					.replace(/\+/g, '%20')) || null
			},
			// 获取openid
			async getOpenId(code) {
				const result = await getOpenid(code)
				console.log('openid', result)
				const openid = result.data.openid
				console.log('openid', result)

				uni.setStorage({
					key: 'openid',
					data: {
						openid: openid
					},
					success: function() {
						console.log('success');
					}
				});

			}
		},
	}
</script>

<style lang="scss">
	@import '@/uni_modules/uview-ui/index.scss'
	/*每个页面公共css */
</style>